package org.example.struct.array;

/**
 * @author liyishan
 * @date 2024/1/3 09:48
 * @apiNote
 */

public class Test00441ArrangeCoins {
    public static void main(String[] args) {
        int res = arrangeCoins3(5);
        System.out.println(res);
    }

    public static int arrangeCoins(int n) {
        if (n == 1) {
            return 1;
        }
        int m = n;
        for (int i = 1; i <= m; i++) {
            n -= i;
            if (n < 0) {
                return i - 1;
            }
        }
        return -1;
    }

    public int arrangeCoins1(int n) {
        return (int) ((Math.sqrt((long) 8 * n + 1) - 1) / 2);
    }

    public static int arrangeCoins3(int n) {
        int left = 1, right = n;
        while (left < right) {
            int mid = left + (right - left + 1) / 2;
            if ((long)mid * (mid + 1) <=(long) 2 * n) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }
}
